package edu.cug.water.crawler.job.controller;

import edu.cug.water.crawler.common.annotation.SysLog;
import edu.cug.water.crawler.common.utils.R;
import edu.cug.water.crawler.job.service.DataStatisticService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.frameworkset.elasticsearch.entity.ESIndice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/data/statistic")
public class DataStatisticController {


    @Autowired
    DataStatisticService dataStatisticService;

    /**
     *
     * @return
     */
    @SysLog("获取ES所有Index")
    @RequestMapping("/indices")
    @RequiresPermissions("sys:schedule:update")
    public R getIndices() {
        List<ESIndice> indices = dataStatisticService.getIndices();

        List<ESIndice> collect = indices.stream().sorted(Comparator.comparing(ESIndice::getDocsCcount, Comparator.reverseOrder())).collect(Collectors.toList());

        List<Map<String, Object>> results = new ArrayList<>();

        try {
            for (ESIndice index : collect) {
                Map describe = BeanUtils.describe(index);
                results.add(describe);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return R.ok().put("indices", results);
    }

    @SysLog("获取所有Indexs的Name")
    @RequestMapping("/getIndexsName")
    public R getIndexsName(){
        return R.ok().put("data", dataStatisticService.getIndexsName());
    }


    @SysLog("获取指定Index的Data")
    @RequestMapping("/getIndexData/{indexName}")
    public R getData(@PathVariable("indexName") String indexName){
        return R.ok().put("data", dataStatisticService.getIndexData(indexName));
    }
}